package com.birboot.core;

import com.birboot.http.HttpServletRequest;
import org.w3c.dom.ls.LSOutput;

import javax.sound.sampled.Line;
import javax.swing.plaf.PanelUI;
import java.io.*;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.SplittableRandom;

public class ClientHandler  implements Runnable {
    private Socket socket;
    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    public void run(){
        try {
            //1解析请求
            //v4：将解析请求的细节移动到request构造器中进行
            HttpServletRequest request = new HttpServletRequest(socket);
            String str = request.getUri();
            System.out.println(str);
            //处理请求

            //3 发送响应
            File baseDir = new File(ClientHandler.class.getClassLoader().getResource(".").toURI());
            File staticDir = new File(baseDir,"static");
            File file = new File(staticDir,str);
            //3.1发送状态
            println("HTTP/1.1 200 OK");
            //3.2发送响应头
            println("Content-Type: text/html");
            println("Content-Length: "+file.length());
            println("");
            //3.3发送响应正文（index.html页面内容）
            OutputStream out = socket.getOutputStream();
            FileInputStream fis = new FileInputStream(file);
            byte[] buf = new byte[1024*10];
            int d;
            while ((d = fis.read(buf))!=-1){
                out.write(buf,0,d);
            }
            /*
            v5的第一个此时目标：将static目录下的index.html页面发送给浏览器
            类加载路径
             */

        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        }
    }
    //向客户端发送一行字符串
    private void println(String line) throws IOException {
        OutputStream out = socket.getOutputStream();
        byte[] data=line.getBytes(StandardCharsets.ISO_8859_1);
        out.write(data);
        out.write(13);//回车
        out.write(10);//换行
    }

    public static void main(String[] args) throws URISyntaxException {
        File baseDir = new File(
                ClientHandler.class.getClassLoader()
                        .getResource(".").toURI()
        );
        //定位类加载路径下的static目录
        File staticDir = new File(baseDir, "static");
        //定位static下的index.html
        File file = new File(staticDir, "index.html");
        System.out.println("页面是否存在:" + file.exists());
    }
}
